package br.senai.sc.controller;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import br.senai.sc.dao.AlunoDAO;
import br.senai.sc.entity.Aluno;


@WebServlet({"/salvarAluno", "/editarAluno", "/excluirAluno", "/listarAluno"})
public class AlunoController extends HttpServlet {

	private static final long serialVersionUID = -3268682322260585177L;
	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {

		String cmd = req.getParameter("cmd");

		if (cmd.equalsIgnoreCase("salvarAluno")) {
			
				String matricula = req.getParameter("matricula");
				String nome = req.getParameter("nome");
				String cpf = req.getParameter("cpf");
				String endereco = req.getParameter("endereco");
				String email = req.getParameter("email");
				String telefone = req.getParameter("telefone");

				Aluno a = new Aluno();
				a.setNome(nome);
				a.setCpf(cpf);
				a.setEndereco(endereco);
				a.setEmail(email);
				a.setTelefone(telefone);

				if (matricula != null) {
					
					int matriculaAux = new Integer(matricula);
					a.setMatricula(matriculaAux);
					AlunoDAO.alterar(a);
				
				} else {
					
					AlunoDAO.inserir(a);
				
				}
				
			resp.sendRedirect("listarAluno?cmd=listarAluno");

		}
	}

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {

		String cmd = req.getParameter("cmd");

		if (cmd.equalsIgnoreCase("editarAluno")) {
			
				String matricula = req.getParameter("matricula");
				Aluno a = new Aluno();
	
				a.setMatricula(Integer.valueOf(matricula));
				Aluno aluno = AlunoDAO.findById(Integer.valueOf(matricula));
	
				req.setAttribute("aluno", aluno);
				req.getRequestDispatcher("/cadastros/cadAluno.jsp").forward(req, resp);


		} else if (cmd.equalsIgnoreCase("listarAluno")) {
	
				List<Aluno> alunos = AlunoDAO.getAll();
	
				req.setAttribute("alunos", alunos);
				req.getRequestDispatcher("cadastros/listarAluno.jsp").forward(req, resp);

		} else if (cmd.equalsIgnoreCase("excluirAluno")) {
			
				Integer matricula = new Integer(req.getParameter("matricula"));
				Aluno a = new Aluno();
				
					if (matricula != 0) {
						
						a.setMatricula(Integer.valueOf(matricula));
						AlunoDAO.excluir(a);
						
					} else {
						
						AlunoDAO.getAll();
						
					}
				resp.sendRedirect("listarAluno?cmd=listarAluno");
		}
	}

}
